﻿using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SmartAgricultureService.Core;
using SmartAgricultureService.Models.Tables;
using SmartAgricultureService.Tables;

namespace SmartAgricultureService.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AreasController(JwtContext jwt, DatabaseContext database, IHttpContextAccessor httpContextAccessor) : ControllerBase(httpContextAccessor)
    {
        [HttpPost("create")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> Create([FromBody] AreaInfo areaInfo)
        {
            try
            {
                var hasArea = await database.Areas.AsNoTracking().AnyAsync(x => (x.Name == areaInfo.Name || x.Code == areaInfo.Code) && !x.Delete);
                if (hasArea)
                    return Reject($"已存在区域名：{areaInfo.Name}或区域编号：{areaInfo.Code}");
                else
                {
                    var areaEntry = new AreaEntry
                    {
                        Active = true,
                        Delete = false,
                        Code = areaInfo.Code,
                        Name = areaInfo.Name,
                        Id = Guid.NewGuid().ToString("N")
                    };
                    await database.Areas.AddAsync(areaEntry);
                    await database.SaveChangesAsync();
                    return Success($"新增区域成功【{areaEntry.Id}】");
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpPost("update")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> Update([FromBody] AreaInfo areaInfo)
        {
            try
            {
                var areaEntry = await database.Areas.FirstOrDefaultAsync(x => x.Id == areaInfo.Id && !x.Delete);
                if (areaEntry == null)
                    return Reject($"不存在区域：{areaInfo.Id}");
                else
                {
                    GetHeader("Authorization", out string token);
                    if (!jwt.IsRoleAt(token, "admin") && areaInfo.Code.Equals("all", StringComparison.CurrentCultureIgnoreCase))
                        return Reject("无效操作！");
                    else
                    {
                        areaEntry.Active = areaInfo.Active;
                        areaEntry.Code = areaInfo.Code;
                        await database.SaveChangesAsync();
                        return Success($"更新区域成功【{areaEntry.Id}】");
                    }
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpDelete("del")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> Delete(string areaId)
        {
            try
            {
                var areaEntry = await database.Areas.AsTracking().FirstOrDefaultAsync(x => x.Id == areaId && !x.Delete);
                if (areaEntry != null)
                {
                    if (!areaEntry.Code.Equals("all", StringComparison.CurrentCultureIgnoreCase))
                    {
                        areaEntry.Active = false;
                        areaEntry.Delete = true;
                        await database.SaveChangesAsync();
                    }
                }
                return Success("删除区域成功");
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpGet("getPaging")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> GetPaging(int pageIndex, string keywords, int pageSize = 15)
        {
            try
            {
                if (pageIndex == 0) pageIndex = 1;
                var areaInfos = await database.Areas.AsNoTracking().Where(x => !x.Delete && (string.IsNullOrEmpty(keywords) || x.Name.Contains(keywords))).Paging(pageIndex, pageSize, out var totalPage).ProjectToType<AreaInfo>(AreaInfo.GetAdapterConfig()).ToListAsync();
                return Paging(pageIndex, totalPage, areaInfos, pageSize);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [AllowAnonymous]
        [HttpGet("getAll")]
        public async Task<IActionResult> GetAll()
        {
            try
            {
                var areaInfos = await database.Areas.AsNoTracking().Where(x => !x.Delete && x.Active).ProjectToType<AreaInfo>(AreaInfo.GetAdapterConfig()).ToListAsync();
                return Success(areaInfos);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
    }
}